// 文件名: ws_client.js
const WebSocket = require("ws");
const crypto = require("crypto");

// WebSocket 地址
const url = "wss://price-ws-r02.speedysurfcdn.net/ws";

// 生成 Sec-WebSocket-Key（Base64 16字节随机数）
const secWebSocketKey = crypto.randomBytes(16).toString("base64");

// 创建 WebSocket 客户端，模拟浏览器头
const ws = new WebSocket(url, "graphql-transport-ws", {
    headers: {
        "Host": "price-ws-r02.speedysurfcdn.net",
        "Connection": "Upgrade",
        "Pragma": "no-cache",
        "Cache-Control": "no-cache",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0",
        "Upgrade": "websocket",
        "Origin": "https://www.baidu.com",
        "Sec-WebSocket-Version": "13",
        "Sec-WebSocket-Key": secWebSocketKey,
        "Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits",
        "Sec-WebSocket-Protocol": "graphql-transport-ws",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"
    }
});

// 打开连接
ws.on("open", () => {
    console.log("✅ WebSocket connected!");

    // 发送初始化授权消息
    const initMsg = {
        type: "connection_init",
        payload: {
            authorization: "gEAmf0vKXACLKcn8NzVkB-A_sNodOr3pBVnTqzQJbmc"
        }
    };

    ws.send(JSON.stringify(initMsg));
});

// 接收消息
ws.on("message", (data) => {
    console.log("📩 Message from server:", data.toString());
});

// 监听错误
ws.on("error", (err) => {
    console.error("❌ WebSocket error:", err);
});

// 监听关闭
ws.on("close", (code, reason) => {
    console.log(`🔒 WebSocket closed: ${code} ${reason}`);
});
